<?php 
require_once dirname(__FILE__) . '/__config.php';
require_once dirname(__FILE__) . '/incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/incls/php/dbutils.class.php';
$myPdo = DbUtils::createPdoInst();

try {
  $mv_fds = scandir('J:/Movies');
  $count = 1;
  foreach ($mv_fds as $idx => &$mv_fd) {
    if ($mv_fd == '.' || $mv_fd == '..') {
      continue;
    }
    
    $cond_vals = new stdClass();
    $cond_vals->c = 't.folder = :v1';
    $cond_vals->v = array(':v1' => $mv_fd);
    $opt = new stdClass();
    $opt->select_expr = 'COUNT(t.id) AS total';
    $total = DbUtils::get($myPdo, 'pz2_mv', $cond_vals, NULL, NULL, NULL, NULL, $opt)->d[0]->total;
    if ($total >= 1) {
      continue;
    }
    
//    $mv_fd = str_replace('@', ':', $mv_fd);
    $mv_obj = json_decode(file_get_contents("http://www.omdbapi.com/?t=" . urlencode ($mv_fd)));
    if ($mv_obj->Response == 'False' || $mv_obj->Type != 'movie') {
      continue;
    }
//    MiscUtils::dump($idx . ' ' . $mv_fd);
//    MiscUtils::dump($mv_obj);
//    MiscUtils::dump('--------------------------------------------------------------------------------------------');
    $mv_obj->folder = $mv_fd;
    add_mv($myPdo, $mv_obj);
    $count++;
    if ($count > 500) {
      break;
    }
  }
} catch (PDOException $e) {
  MiscUtils::dump($e);
}

function add_mv($myPdo, $mv_obj) {
  DbUtils::add($myPdo, 'pz2_mv', __conv_obj($mv_obj));
}

function __conv_obj($mv_obj) {
  $new_obj = new stdClass();
  foreach ($mv_obj as $key => &$val) {
    $new_key = strtolower($key);
    $new_obj->$new_key = $val;
  }
  $new_obj->imdbvotes = str_replace(',', '', $new_obj->imdbvotes);
  unset($new_obj->response);
  unset($new_obj->released);
  if (!is_numeric((string)$new_obj->year)) {
    $new_obj->year = -1;
  }
  if (!is_numeric((string)$new_obj->imdbrating)) {
    $new_obj->imdbrating = -1;
  }
  if (!is_numeric((string)$new_obj->imdbvotes)) {
    $new_obj->imdbvotes = -1;
  }
  return $new_obj;
}
?>
